package com.xyebank.ledger.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 *
 *@author wxh
 *@date 2017年3月10日--下午6:18:08
 */
public class RainbowExceptionUtil {
	
	private static final Map<String, String> exceptions = new HashMap<>();
	private static final String prefix = "com.xyebank.rainbow.exception";
	private static final Logger logger = LoggerFactory.getLogger(RainbowExceptionUtil.class);
	
	static {
		FileInputStream fis = null;
		try {
			ResourceBundle resourceBundle = ResourceBundle.getBundle("exceptions");
			Enumeration<String> es = resourceBundle.getKeys();
			while(es.hasMoreElements()) {
				String key = es.nextElement();
				exceptions.put(key, resourceBundle.getString(key));
			}
			Properties prop = new Properties();
			fis = new FileInputStream("/home/service/core_conf/rainbow_ledger_exceptions.properties");
			prop.load(fis);
			for(Object ko : prop.keySet()) {
				exceptions.put((String) ko, prop.getProperty((String) ko));
			}
		} catch(Exception e) {
			logger.warn("加载异常配置文件出现错误:{},详细信息:{}",e.getMessage(),e.getStackTrace());
		} finally {
			if(fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static String getMsg(int code, Object... params) {
		String msg = null;
		try {
			msg = exceptions.get(prefix + "." + code);
		} catch(Exception e) {
			logger.warn("get msg err, code : {}, message : {}.", code+"", e.getMessage());
			return msg;
		}
		if(msg != null) {
			if(params != null && params.length > 0) {
				for(int i = 0; i < params.length; i++) {
					String ex = "";
					if(params[i] != null) {
						ex = params[i].toString();
					}
					msg = msg.replace("{"+i+"}", ex);
				}
			}
		}
		return msg;
	}
	
}
